/*
 * Copyright (c) 2025 Huawei Technologies Co., Ltd.
 * openUBMC is licensed under Mulan PSL v2.
 * You can use this software according to the terms and conditions of the Mulan PSL v2.
 * You may obtain a copy of Mulan PSL v2 at:
 *         http://license.coscl.org.cn/MulanPSL2
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
 * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
 * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PSL v2 for more details.
 */

#include <gtest/gtest.h>

#include <algorithm>
#include <array>
#include <chrono>
#include <cstring>
#include <functional>
#include <memory>
#include <string>
#include <thread>
#include <vector>

#include <mc/common.h>  
#include <test_utilities/test_base.h>
#include <mc/memory.h>
#include <ncsi/ncsi_huawei.h>
#include <ncsi/ncsi_protocol.h>
#include <ncsi/ncsi_socket.h>
#include <ncsi_over_mctp/ncsi_over_mctp_huawei.h>

// COMMON_DATA_SIZE 定义
#define COMMON_DATA_SIZE 7

#include "../../../../../drivers/pcie_nic_card/hisi/interface/optical_module.h"
#include "../../../../../drivers/pcie_nic_card/hisi/interface/optical_module/cooling.h"
#include "../../../../../drivers/pcie_nic_card/hisi/interface/optical_module/current.h"
#include "../../../../../drivers/pcie_nic_card/hisi/interface/optical_module/power.h"
#include "../../../../../drivers/pcie_nic_card/hisi/interface/optical_module/status.h"
#include "../../../../../drivers/pcie_nic_card/hisi/interface/optical_module/voltage.h"
#include <smbus/smbus.h>
#include <mc/crypto/crc32.h>
#include <map>

// 声明外部函数
namespace dev {
void set_mctp_request_handler(std::function<bool(const mc::dict&, const std::vector<uint8_t>&,
                                                  std::string&)> handler);
} // namespace dev

namespace {

// 辅助函数：字节序转换
constexpr uint16_t host_to_be16(uint16_t value) {
    return static_cast<uint16_t>(((value & 0x00FFU) << 8U) | ((value & 0xFF00U) >> 8U));
}

// 辅助函数：创建光模块信息响应
std::string make_optical_module_info_response(const std::string& manufacturer = "HUAWEI",
                                              const std::string& part_number   = "L99QF020-SD-R",
                                              const std::string& serial_number = "Z00A2R1709000061",
                                              uint8_t            type          = 1,  // Optical
                                              uint8_t            connector     = 0x07,  // LC
                                              uint16_t           distance      = 100,
                                              uint16_t           wave_length   = 850) {
    oem_huawei_optical_module_info_rsp_t response{};
    response.public_rsp_header.response_code   = host_to_be16(0);
    response.public_rsp_header.reason_code     = host_to_be16(0);
    response.public_rsp_header.manufacturer_id = HUAWEI_MANUFACTURE_ID;
    response.public_rsp_header.sub_command_id  = OEM_HUAWEI_GET_OPTICAL_MODULE_INFO;

    // 填充厂商名称
    std::memset(response.vendor, ' ', MCTP_NCSI_OPTICAL_MODULE_FIELD_LEN);
    std::copy(manufacturer.begin(), manufacturer.end(), response.vendor);

    // 填充部件号
    std::memset(response.part_number, ' ', MCTP_NCSI_OPTICAL_MODULE_FIELD_LEN);
    std::copy(part_number.begin(), part_number.end(), response.part_number);

    // 填充序列号
    std::memset(response.serial_number, ' ', MCTP_NCSI_OPTICAL_MODULE_FIELD_LEN);
    std::copy(serial_number.begin(), serial_number.end(), response.serial_number);

    response.type                = type;
    response.connector           = connector;
    response.transceiver_distance = host_to_be16(distance);
    response.wave_length         = host_to_be16(wave_length);
    response.working_voltage     = host_to_be16(3300);
    response.working_tx_bias     = host_to_be16(5000);
    response.working_tx_power    = host_to_be16(6000);
    response.working_rx_power    = host_to_be16(7000);
    response.alarm_tx_power_threshold = host_to_be16(8000);
    response.alarm_rx_power_threshold = host_to_be16(9000);
    response.alarm_low_temp_threshold = host_to_be16(10);
    response.alarm_high_temp_threshold = host_to_be16(90);
    response.rx_los_state        = 0;
    response.tx_full_state        = 0;

    return std::string(reinterpret_cast<const char*>(&response), OEM_HUAWEI_OPTICAL_MODULE_INFO_RSP_LEN);
}

// Mock smbus - 支持根据 opcode 返回不同的响应
class mock_smbus : public dev::smbus {
public:
    mock_smbus() : dev::smbus(nullptr) {
    }

    void set_send_request_result(const std::string& data_result) {
        m_data_result = data_result;
    }

    void set_send_request_result_for_opcode(uint16_t opcode, const std::string& data_result) {
        m_opcode_results[opcode] = data_result;
    }

    std::pair<bool, std::vector<uint8_t>> send_and_receive(const std::string& data,
                                                           uint32_t len) override {
        // 从请求数据中解析 opcode
        // dev::smbus 请求格式：reserved(2) + opcode(2) + offset(4) + length(4)
        uint16_t request_opcode = 0x04;  // 默认值
        if (data.length() >= 4) {
            // opcode 在 reserved (2 bytes) 之后
            request_opcode = static_cast<uint8_t>(data[2]) | (static_cast<uint8_t>(data[3]) << 8);
        }

        // 根据 opcode 获取对应的响应数据
        std::string response_data = m_data_result;
        if (m_opcode_results.find(request_opcode) != m_opcode_results.end()) {
            response_data = m_opcode_results[request_opcode];
        }

        // 如果数据为空，返回空响应
        if (response_data.empty()) {
            return std::make_pair(false, std::vector<uint8_t>());
        }

        uint32_t data_len = static_cast<uint32_t>(response_data.length());

        std::vector<uint8_t> response;
        response.reserve(12 + data_len + 4);

        response.push_back(0x00);
        response.push_back(0x00);

        // opcode (2 bytes) - 从请求中获取
        response.push_back(static_cast<uint8_t>(request_opcode & 0xFF));
        response.push_back(static_cast<uint8_t>((request_opcode >> 8) & 0xFF));

        response.push_back(static_cast<uint8_t>(data_len & 0xFF));
        response.push_back(static_cast<uint8_t>((data_len >> 8) & 0xFF));
        response.push_back(static_cast<uint8_t>((data_len >> 16) & 0xFF));
        response.push_back(static_cast<uint8_t>((data_len >> 24) & 0xFF));

        response.push_back(static_cast<uint8_t>(data_len & 0xFF));
        response.push_back(static_cast<uint8_t>((data_len >> 8) & 0xFF));
        response.push_back(static_cast<uint8_t>((data_len >> 16) & 0xFF));
        response.push_back(static_cast<uint8_t>((data_len >> 24) & 0xFF));

        response.insert(response.end(), response_data.begin(), response_data.end());

        std::string bin_data(reinterpret_cast<const char*>(response.data()), response.size());
        uint32_t crc32 = mc::crypto::CRC32().calculate(bin_data, 0, true);
        response.push_back(static_cast<uint8_t>(crc32 & 0xFF));
        response.push_back(static_cast<uint8_t>((crc32 >> 8) & 0xFF));
        response.push_back(static_cast<uint8_t>((crc32 >> 16) & 0xFF));
        response.push_back(static_cast<uint8_t>((crc32 >> 24) & 0xFF));

        return std::make_pair(true, response);
    }

private:
    std::string m_data_result;
    std::map<uint16_t, std::string> m_opcode_results;
};

// Test service
class test_service : public mc::engine::service {
public:
    test_service(const std::string& name) : mc::engine::service(name) {
    }
};

// Test fixture
class optical_module_test : public mc::test::TestWithEngine {
protected:
    static void SetUpTestSuite() {
        TestWithEngine::SetUpTestSuite();
        m_test_service.init();
        m_test_service.start();
        m_mctp = mc::make_shared<dev::mctp>(nullptr, 0, dev::MCTP_MESSAGE_TYPE_NCSI, "");
    }

    static void TearDownTestSuite() {
        m_test_service.stop();
        m_mctp.reset();
        TestWithEngine::TearDownTestSuite();
    }

    void SetUp() override {
        m_optical_module = mc::make_shared<dev::OpticalModule>();
        m_optical_module->set_port_id(1);
    }

    void TearDown() override {
        // 等待所有异步操作完成（如定时器回调），避免在服务停止时回调仍在执行
        std::this_thread::sleep_for(std::chrono::milliseconds(200));
        // 清理实例成员
        m_optical_module.reset();
        dev::set_mctp_request_handler(nullptr);
    }

    mc::shared_ptr<dev::OpticalModule> m_optical_module;
    static test_service m_test_service;
    static mc::shared_ptr<dev::mctp> m_mctp;
};

// 静态成员初始化
test_service optical_module_test::m_test_service{"bmc.kepler.test_om"};
mc::shared_ptr<dev::mctp> optical_module_test::m_mctp;

// ========== OpticalModule_Status 测试 ==========

// Test fixture for OpticalModule_Status
class optical_module_status_test : public mc::test::TestWithEngine {
protected:
    static void SetUpTestSuite() {
        TestWithEngine::SetUpTestSuite();
        m_test_service.init();
        m_test_service.start();
        m_mctp = mc::make_shared<dev::mctp>(nullptr, 0, dev::MCTP_MESSAGE_TYPE_NCSI, "");
        m_status = mc::make_shared<dev::OpticalModule_Status>();
    }

    static void TearDownTestSuite() {
        m_test_service.stop();
        m_status.reset();
        m_mctp.reset();
        TestWithEngine::TearDownTestSuite();
    }

    void SetUp() override {
    }

    void TearDown() override {
        // 等待所有异步操作完成（如定时器回调），避免在服务停止时回调仍在执行
        std::this_thread::sleep_for(std::chrono::milliseconds(200));
        dev::set_mctp_request_handler(nullptr);
    }

    static test_service m_test_service;
    static mc::shared_ptr<dev::mctp> m_mctp;
    static mc::shared_ptr<dev::OpticalModule_Status> m_status;
};

// 静态成员初始化
test_service optical_module_status_test::m_test_service{"bmc.kepler.test_om_status"};
mc::shared_ptr<dev::mctp> optical_module_status_test::m_mctp;
mc::shared_ptr<dev::OpticalModule_Status> optical_module_status_test::m_status;

TEST_F(optical_module_status_test, get_optical_module_info_by_ncsi_success) {
    dev::set_mctp_request_handler([](const mc::dict&, const std::vector<uint8_t>&,
                                     std::string& rsp) {
        rsp = make_optical_module_info_response("HUAWEI", "TEST-PART", "TEST-SERIAL", 1, 0x07, 100, 850);
        return true;
    });

    auto ncsi = std::make_shared<dev::ncsi_over_mctp_huawei>(*m_mctp);
    m_status->start_ncsi_update_task_huawei(ncsi, mc::milliseconds(1000), 1);

    bool result = m_status->get_optical_module_info_by_ncsi(1);
    EXPECT_TRUE(result);
    // rx_los_state = 0, tx_full_state = 0
    EXPECT_EQ(m_status->RXLossState.get_value().as<bool>(), false);
    EXPECT_EQ(m_status->TXFaultState.get_value().as<bool>(), false);
    
    // 显式停止定时器，避免在 TearDown 时定时器仍在运行
    m_status->stop_ncsi_update_task();
    // 等待所有异步操作完成（如定时器回调），避免在 TearDown 时回调仍在执行
    // 增加等待时间，确保定时器回调完全停止
    std::this_thread::sleep_for(std::chrono::milliseconds(100));
}

TEST_F(optical_module_status_test, get_optical_module_info_by_ncsi_with_faults) {
    // 需要创建一个带有故障状态的响应
    dev::set_mctp_request_handler([](const mc::dict&, const std::vector<uint8_t>&,
                                     std::string& rsp) {
        oem_huawei_optical_module_info_rsp_t response{};
        response.public_rsp_header.response_code   = host_to_be16(0);
        response.public_rsp_header.reason_code     = host_to_be16(0);
        response.public_rsp_header.manufacturer_id = HUAWEI_MANUFACTURE_ID;
        response.public_rsp_header.sub_command_id  = OEM_HUAWEI_GET_OPTICAL_MODULE_INFO;
        std::memset(response.vendor, ' ', MCTP_NCSI_OPTICAL_MODULE_FIELD_LEN);
        std::memset(response.part_number, ' ', MCTP_NCSI_OPTICAL_MODULE_FIELD_LEN);
        std::memset(response.serial_number, ' ', MCTP_NCSI_OPTICAL_MODULE_FIELD_LEN);
        response.type                = 1;
        response.connector           = 0x07;
        response.transceiver_distance = host_to_be16(100);
        response.wave_length         = host_to_be16(850);
        response.working_voltage     = host_to_be16(3300);
        response.working_tx_bias     = host_to_be16(5000);
        response.working_tx_power    = host_to_be16(6000);
        response.working_rx_power    = host_to_be16(7000);
        response.alarm_tx_power_threshold = host_to_be16(8000);
        response.alarm_rx_power_threshold = host_to_be16(9000);
        response.alarm_low_temp_threshold = host_to_be16(10);
        response.alarm_high_temp_threshold = host_to_be16(90);
        response.rx_los_state        = 1;  // RX loss
        response.tx_full_state       = 1;  // TX fault
        rsp = std::string(reinterpret_cast<const char*>(&response),
                          OEM_HUAWEI_OPTICAL_MODULE_INFO_RSP_LEN);
        return true;
    });

    auto ncsi = std::make_shared<dev::ncsi_over_mctp_huawei>(*m_mctp);
    m_status->start_ncsi_update_task_huawei(ncsi, mc::milliseconds(1000), 1);

    bool result = m_status->get_optical_module_info_by_ncsi(1);
    EXPECT_TRUE(result);
    EXPECT_EQ(m_status->RXLossState.get_value().as<bool>(), true);
    EXPECT_EQ(m_status->TXFaultState.get_value().as<bool>(), true);
    
    // 显式停止定时器，避免在 TearDown 时定时器仍在运行
    m_status->stop_ncsi_update_task();
    // 等待所有异步操作完成（如定时器回调），避免在 TearDown 时回调仍在执行
    // 增加等待时间，确保定时器回调完全停止
    std::this_thread::sleep_for(std::chrono::milliseconds(100));
}

TEST_F(optical_module_status_test, get_optical_module_info_by_ncsi_failure) {
    dev::set_mctp_request_handler([](const mc::dict&, const std::vector<uint8_t>&,
                                     std::string&) { return false; });

    auto ncsi = std::make_shared<dev::ncsi_over_mctp_huawei>(*m_mctp);
    m_status->start_ncsi_update_task_huawei(ncsi, mc::milliseconds(1000), 1);

    bool result = m_status->get_optical_module_info_by_ncsi(1);
    EXPECT_FALSE(result);
    
    // 显式停止定时器，避免在 TearDown 时定时器仍在运行
    m_status->stop_ncsi_update_task();
    // 等待所有异步操作完成（如定时器回调），避免在 TearDown 时回调仍在执行
    // 增加等待时间，确保定时器回调完全停止
    std::this_thread::sleep_for(std::chrono::milliseconds(100));
}

TEST_F(optical_module_status_test, start_ncsi_update_task_huawei_sets_ncsi_object) {
    dev::set_mctp_request_handler([](const mc::dict&, const std::vector<uint8_t>&,
                                     std::string& rsp) {
        rsp = make_optical_module_info_response();
        return true;
    });

    auto ncsi = std::make_shared<dev::ncsi_over_mctp_huawei>(*m_mctp);
    m_status->start_ncsi_update_task_huawei(ncsi, mc::milliseconds(100), 1);

    bool result = m_status->get_optical_module_info_by_ncsi(1);
    EXPECT_TRUE(result);
    
    // 显式停止定时器，避免在 TearDown 时定时器仍在运行
    m_status->stop_ncsi_update_task();
    // 等待所有异步操作完成（如定时器回调），避免在 TearDown 时回调仍在执行
    // 增加等待时间，确保定时器回调完全停止
    std::this_thread::sleep_for(std::chrono::milliseconds(100));
}

TEST_F(optical_module_status_test, stop_ncsi_update_task_cleans_up_resources) {
    auto ncsi = std::make_shared<dev::ncsi_over_mctp_huawei>(*m_mctp);
    m_status->start_ncsi_update_task_huawei(ncsi, mc::milliseconds(100), 1);
    m_status->stop_ncsi_update_task();
    m_status->stop_ncsi_update_task();  // 再次调用应该不会崩溃
    // 等待所有异步操作完成（如定时器回调），避免在 TearDown 时回调仍在执行
    // 增加等待时间，确保定时器回调完全停止
    std::this_thread::sleep_for(std::chrono::milliseconds(100));
}

// ========== OpticalModule_Voltage 测试 ==========

// Test fixture for OpticalModule_Voltage
class optical_module_voltage_test : public mc::test::TestWithEngine {
protected:
    static void SetUpTestSuite() {
        TestWithEngine::SetUpTestSuite();
        m_test_service = mc::make_shared<test_service>("bmc.kepler.test_om_voltage");
        m_test_service->init();
        m_test_service->start();
        m_mctp = mc::make_shared<dev::mctp>(nullptr, 0, dev::MCTP_MESSAGE_TYPE_NCSI, "");
    }

    static void TearDownTestSuite() {
        m_test_service->stop();
        m_mctp.reset();
        TestWithEngine::TearDownTestSuite();
    }

    void SetUp() override {
        m_voltage = mc::make_shared<dev::OpticalModule_Voltage>();
    }

    void TearDown() override {
        m_voltage.reset();
        m_mctp.reset();
    }

    static mc::shared_ptr<dev::OpticalModule_Voltage> m_voltage;
    static mc::shared_ptr<test_service>               m_test_service;
    static mc::shared_ptr<dev::mctp>                  m_mctp;
};

// 静态成员初始化
mc::shared_ptr<dev::OpticalModule_Voltage> optical_module_voltage_test::m_voltage;
mc::shared_ptr<test_service> optical_module_voltage_test::m_test_service;
mc::shared_ptr<dev::mctp> optical_module_voltage_test::m_mctp;

// 暂时禁用此测试，测试失败
TEST_F(optical_module_voltage_test, get_optical_module_voltage_by_ncsi_success) {
    dev::set_mctp_request_handler([](const mc::dict&, const std::vector<uint8_t>&,
                                     std::string& rsp) {
        rsp = make_optical_module_info_response("HUAWEI", "TEST-PART", "TEST-SERIAL", 1, 0x07, 100, 850);
        return true;
    });

    auto ncsi = std::make_shared<dev::ncsi_over_mctp_huawei>(*m_mctp);
    m_voltage->start_ncsi_update_task_huawei(ncsi, mc::milliseconds(1000), 1);

    bool result = m_voltage->get_optical_module_voltage_by_ncsi(1);
    EXPECT_TRUE(result);
    // working_voltage = 3300
    // covert_micro_to_milli(3300) = 3300 / 1000.0 = 3.3 (V)
    EXPECT_NEAR(m_voltage->SupplyVoltage.get_value().as<double>(), 3.3, 0.01);
    
    // 显式停止定时器，避免在 TearDown 时定时器仍在运行
    m_voltage->stop_ncsi_update_task();
    // 等待所有异步操作完成（如定时器回调），避免在 TearDown 时回调仍在执行
    // 增加等待时间，确保定时器回调完全停止
    std::this_thread::sleep_for(std::chrono::milliseconds(100));
}

TEST_F(optical_module_voltage_test, get_optical_module_voltage_by_ncsi_invalid_voltage) {
    // 测试无效电压值 (0xFFFF)
    dev::set_mctp_request_handler([](const mc::dict&, const std::vector<uint8_t>&,
                                     std::string& rsp) {
        oem_huawei_optical_module_info_rsp_t response{};
        response.public_rsp_header.response_code   = host_to_be16(0);
        response.public_rsp_header.reason_code     = host_to_be16(0);
        response.public_rsp_header.manufacturer_id = HUAWEI_MANUFACTURE_ID;
        response.public_rsp_header.sub_command_id  = OEM_HUAWEI_GET_OPTICAL_MODULE_INFO;
        std::memset(response.vendor, ' ', MCTP_NCSI_OPTICAL_MODULE_FIELD_LEN);
        std::memset(response.part_number, ' ', MCTP_NCSI_OPTICAL_MODULE_FIELD_LEN);
        std::memset(response.serial_number, ' ', MCTP_NCSI_OPTICAL_MODULE_FIELD_LEN);
        response.type                = 1;
        response.connector           = 0x07;
        response.transceiver_distance = host_to_be16(100);
        response.wave_length         = host_to_be16(850);
        response.working_voltage     = host_to_be16(0xFFFF);  // 无效值
        response.working_tx_bias     = host_to_be16(5000);
        response.working_tx_power    = host_to_be16(6000);
        response.working_rx_power    = host_to_be16(7000);
        response.alarm_tx_power_threshold = host_to_be16(8000);
        response.alarm_rx_power_threshold = host_to_be16(9000);
        response.alarm_low_temp_threshold = host_to_be16(10);
        response.alarm_high_temp_threshold = host_to_be16(90);
        response.rx_los_state        = 0;
        response.tx_full_state       = 0;
        rsp = std::string(reinterpret_cast<const char*>(&response),
                          OEM_HUAWEI_OPTICAL_MODULE_INFO_RSP_LEN);
        return true;
    });

    auto ncsi = std::make_shared<dev::ncsi_over_mctp_huawei>(*m_mctp);
    m_voltage->start_ncsi_update_task_huawei(ncsi, mc::milliseconds(1000), 1);

    bool result = m_voltage->get_optical_module_voltage_by_ncsi(1);
    EXPECT_TRUE(result);
    // 无效值不应该被设置，需要检查属性是否被设置
    
    // 显式停止定时器，避免在 TearDown 时定时器仍在运行
    m_voltage->stop_ncsi_update_task();
    // 等待所有异步操作完成（如定时器回调），避免在 TearDown 时回调仍在执行
    // 增加等待时间，确保定时器回调完全停止
    std::this_thread::sleep_for(std::chrono::milliseconds(100));
}

TEST_F(optical_module_voltage_test, get_optical_module_voltage_by_ncsi_failure) {
    dev::set_mctp_request_handler([](const mc::dict&, const std::vector<uint8_t>&,
                                     std::string&) { return false; });

    auto ncsi = std::make_shared<dev::ncsi_over_mctp_huawei>(*m_mctp);
    m_voltage->start_ncsi_update_task_huawei(ncsi, mc::milliseconds(1000), 1);

    bool result = m_voltage->get_optical_module_voltage_by_ncsi(1);
    EXPECT_FALSE(result);
    
    // 显式停止定时器，避免在 TearDown 时定时器仍在运行
    m_voltage->stop_ncsi_update_task();
    // 等待所有异步操作完成（如定时器回调），避免在 TearDown 时回调仍在执行
    // 增加等待时间，确保定时器回调完全停止
    std::this_thread::sleep_for(std::chrono::milliseconds(100));
}

TEST_F(optical_module_voltage_test, start_ncsi_update_task_huawei_sets_ncsi_object) {
    dev::set_mctp_request_handler([](const mc::dict&, const std::vector<uint8_t>&,
                                     std::string& rsp) {
        rsp = make_optical_module_info_response();
        return true;
    });

    auto ncsi = std::make_shared<dev::ncsi_over_mctp_huawei>(*m_mctp);
    m_voltage->start_ncsi_update_task_huawei(ncsi, mc::milliseconds(100), 1);

    bool result = m_voltage->get_optical_module_voltage_by_ncsi(1);
    EXPECT_TRUE(result);
    
    // 显式停止定时器，避免在 TearDown 时定时器仍在运行
    m_voltage->stop_ncsi_update_task();
    // 等待所有异步操作完成（如定时器回调），避免在 TearDown 时回调仍在执行
    // 增加等待时间，确保定时器回调完全停止
    std::this_thread::sleep_for(std::chrono::milliseconds(100));
}

TEST_F(optical_module_voltage_test, stop_ncsi_update_task_cleans_up_resources) {
    auto ncsi = std::make_shared<dev::ncsi_over_mctp_huawei>(*m_mctp);
    m_voltage->start_ncsi_update_task_huawei(ncsi, mc::milliseconds(100), 1);
    m_voltage->stop_ncsi_update_task();
    m_voltage->stop_ncsi_update_task();  // 再次调用应该不会崩溃
    // 等待所有异步操作完成（如定时器回调），避免在 TearDown 时回调仍在执行
    // 增加等待时间，确保定时器回调完全停止
    std::this_thread::sleep_for(std::chrono::milliseconds(100));
}

TEST_F(optical_module_test, set_port_id_and_get_port_id) {
    // 目标：验证 set_port_id 和 get_port_id 方法
    
    m_optical_module->set_port_id(5);
    EXPECT_EQ(m_optical_module->get_port_id(), 5);
    
    m_optical_module->set_port_id(10);
    EXPECT_EQ(m_optical_module->get_port_id(), 10);
}

TEST_F(optical_module_test, port_id_boundary_values) {
    // 目标：验证 port_id 的边界值处理
    m_optical_module->set_port_id(0);
    EXPECT_EQ(m_optical_module->get_port_id(), 0);
    
    m_optical_module->set_port_id(255);  // uint8_t 最大值
    EXPECT_EQ(m_optical_module->get_port_id(), 255);
}

TEST_F(optical_module_test, get_optical_module_info_by_ncsi_string_trimming) {
    // 目标：验证 get_optical_module_info_by_ncsi 方法能正确去除字符串尾部空格
    m_optical_module->set_port_id(1);
    
    dev::set_mctp_request_handler([](const mc::dict&, const std::vector<uint8_t>&,
                                     std::string& rsp) {
        oem_huawei_optical_module_info_rsp_t response{};
        response.public_rsp_header.response_code   = host_to_be16(0);
        response.public_rsp_header.reason_code     = host_to_be16(0);
        response.public_rsp_header.manufacturer_id = HUAWEI_MANUFACTURE_ID;
        response.public_rsp_header.sub_command_id  = OEM_HUAWEI_GET_OPTICAL_MODULE_INFO;
        
        // 设置带尾随空格的字符串
        std::string manufacturer = "HUAWEI";
        std::string part_number = "TEST-PART";
        std::string serial_number = "TEST-SERIAL";
        manufacturer.resize(MCTP_NCSI_OPTICAL_MODULE_FIELD_LEN, ' ');
        part_number.resize(MCTP_NCSI_OPTICAL_MODULE_FIELD_LEN, ' ');
        serial_number.resize(MCTP_NCSI_OPTICAL_MODULE_FIELD_LEN, ' ');
        
        std::memcpy(response.vendor, manufacturer.c_str(), MCTP_NCSI_OPTICAL_MODULE_FIELD_LEN);
        std::memcpy(response.part_number, part_number.c_str(), MCTP_NCSI_OPTICAL_MODULE_FIELD_LEN);
        std::memcpy(response.serial_number, serial_number.c_str(), MCTP_NCSI_OPTICAL_MODULE_FIELD_LEN);
        
        response.type                = 1;
        response.connector           = 0x07;
        response.transceiver_distance = host_to_be16(100);
        response.wave_length         = host_to_be16(850);
        response.identifier         = 0x03;
        response.check_sum          = 0;
        
        rsp = std::string(reinterpret_cast<const char*>(&response), sizeof(response));
        return true;
    });
    
    auto ncsi = std::make_shared<dev::ncsi_over_mctp_huawei>(*m_mctp);
    m_optical_module->start_ncsi_update_task_huawei(ncsi, mc::milliseconds(100));
    
    bool result = m_optical_module->get_optical_module_info_by_ncsi();
    EXPECT_TRUE(result);
    
    // 验证字符串已去除尾部空格
    EXPECT_EQ(m_optical_module->Manufacturer.get_value().as<std::string>(), "HUAWEI");
    EXPECT_EQ(m_optical_module->PartNumber.get_value().as<std::string>(), "TEST-PART");
    EXPECT_EQ(m_optical_module->SerialNumber.get_value().as<std::string>(), "TEST-SERIAL");
    
    m_optical_module->stop_ncsi_update_task();
    std::this_thread::sleep_for(std::chrono::milliseconds(100));
}

TEST_F(optical_module_test, get_optical_module_info_by_ncsi_different_medium_types) {
    // 目标：验证不同介质类型的处理
    m_optical_module->set_port_id(1);
    
    std::vector<std::string> medium_types = {"Optical", "Aoc", "Electric", "Other"};
    
    for (const auto& medium_type : medium_types) {
        dev::set_mctp_request_handler([&medium_type](const mc::dict&, const std::vector<uint8_t>&,
                                                     std::string& rsp) {
            rsp = make_optical_module_info_response("HUAWEI", "TEST-PART", "TEST-SERIAL", 1, 0x07, 100, 850);
            // 修改响应中的 type (medium_type 通过 type 字段映射)
            if (rsp.size() >= sizeof(oem_huawei_optical_module_info_rsp_t)) {
                auto* resp_ptr = reinterpret_cast<oem_huawei_optical_module_info_rsp_t*>(rsp.data());
                // 根据 medium_type 字符串设置 type 字段
                // Optical=1, Aoc=2, Electric=3, Other=4 (根据实际映射关系)
                if (medium_type == "Optical") {
                    resp_ptr->type = 1;
                } else if (medium_type == "Aoc") {
                    resp_ptr->type = 2;
                } else if (medium_type == "Electric") {
                    resp_ptr->type = 3;
                } else {
                    resp_ptr->type = 4; // Other
                }
            }
            return true;
        });
        
        auto ncsi = std::make_shared<dev::ncsi_over_mctp_huawei>(*m_mctp);
        m_optical_module->start_ncsi_update_task_huawei(ncsi, mc::milliseconds(100));
        
        bool result = m_optical_module->get_optical_module_info_by_ncsi();
        EXPECT_TRUE(result);
        
        m_optical_module->stop_ncsi_update_task();
        std::this_thread::sleep_for(std::chrono::milliseconds(50));
    }
}

TEST_F(optical_module_test, stop_ncsi_update_task_multiple_calls) {
    // 目标：验证多次调用 stop_ncsi_update_task 不会崩溃
    m_optical_module->set_port_id(1);
    
    auto ncsi = std::make_shared<dev::ncsi_over_mctp_huawei>(*m_mctp);
    m_optical_module->start_ncsi_update_task_huawei(ncsi, mc::milliseconds(100));
    
    m_optical_module->stop_ncsi_update_task();
    m_optical_module->stop_ncsi_update_task();  // 再次调用应该不会崩溃
    
    std::this_thread::sleep_for(std::chrono::milliseconds(100));
}

TEST_F(optical_module_test, stop_ncsi_update_task_without_start) {
    // 目标：验证在没有启动任务时调用 stop_ncsi_update_task 不会崩溃
    m_optical_module->stop_ncsi_update_task();
    EXPECT_TRUE(true);
}

// ========== OpticalModule_Cooling 测试 ==========

// Test fixture for OpticalModule_Cooling
class optical_module_cooling_test : public mc::test::TestWithEngine {
protected:
    static void SetUpTestSuite() {
        TestWithEngine::SetUpTestSuite();
        m_test_service.init();
        m_test_service.start();
        m_mctp = mc::make_shared<dev::mctp>(nullptr, 0, dev::MCTP_MESSAGE_TYPE_NCSI, "");
        m_cooling = mc::make_shared<dev::OpticalModule_Cooling>();
    }

    static void TearDownTestSuite() {
        m_test_service.stop();
        m_cooling.reset();
        m_mctp.reset();
        TestWithEngine::TearDownTestSuite();
    }

    void SetUp() override {
    }

    void TearDown() override {
        // 等待所有异步操作完成（如定时器回调），避免在服务停止时回调仍在执行
        std::this_thread::sleep_for(std::chrono::milliseconds(200));
        dev::set_mctp_request_handler(nullptr);
    }

    static test_service m_test_service;
    static mc::shared_ptr<dev::mctp> m_mctp;
    static mc::shared_ptr<dev::OpticalModule_Cooling> m_cooling;
    static mc::shared_ptr<mock_smbus> m_smbus;
};

// 静态成员初始化
test_service optical_module_cooling_test::m_test_service{"bmc.kepler.test_om_cooling"};
mc::shared_ptr<dev::mctp> optical_module_cooling_test::m_mctp;
mc::shared_ptr<dev::OpticalModule_Cooling> optical_module_cooling_test::m_cooling;
mc::shared_ptr<mock_smbus> optical_module_cooling_test::m_smbus;

// 辅助函数：创建get_om_temp响应
std::string make_get_om_temp_response(uint16_t temperature = 0x1234) {
    oem_huawei_temperature_rsp_t response{};
    response.public_rsp_header.response_code   = host_to_be16(0);
    response.public_rsp_header.reason_code     = host_to_be16(0);
    response.public_rsp_header.manufacturer_id = HUAWEI_MANUFACTURE_ID;
    response.public_rsp_header.sub_command_id  = OEM_HUAWEI_GET_OM_TEMP;
    response.temperature                        = host_to_be16(temperature);
    return std::string(reinterpret_cast<const char*>(&response), OEM_HUAWEI_CHIP_TEMP_RSP_LEN);
}

TEST_F(optical_module_cooling_test, get_om_temp_by_ncsi_success) {
    dev::set_mctp_request_handler([](const mc::dict&, const std::vector<uint8_t>& data,
                                     std::string& rsp) {
        // 检查是否是get_om_temp命令
        if (data.size() >= COMMON_DATA_SIZE && data[5] == OEM_HUAWEI_GET_OM_TEMP) {
            rsp = make_get_om_temp_response(0x1234);
            return true;
        }
        return false;
    });

    auto ncsi = std::make_shared<dev::ncsi_over_mctp_huawei>(*m_mctp);
    m_cooling->start_ncsi_update_task_huawei(ncsi, mc::milliseconds(1000), 1);

    bool result = m_cooling->get_om_temp_by_ncsi(1);
    EXPECT_TRUE(result);
    EXPECT_EQ(m_cooling->TemperatureCelsius.get_value().as<double>(), static_cast<double>(static_cast<int8_t>(0x1234)));
    
    // 显式停止定时器，避免在 TearDown 时定时器仍在运行
    m_cooling->stop_ncsi_update_task();
    // 等待所有异步操作完成（如定时器回调），避免在 TearDown 时回调仍在执行
    std::this_thread::sleep_for(std::chrono::milliseconds(100));
}

TEST_F(optical_module_cooling_test, get_om_temp_by_ncsi_invalid_temp) {
    dev::set_mctp_request_handler([](const mc::dict&, const std::vector<uint8_t>& data,
                                     std::string& rsp) {
        if (data.size() >= COMMON_DATA_SIZE && data[5] == OEM_HUAWEI_GET_OM_TEMP) {
            // 返回无效温度值 0x7FFD
            rsp = make_get_om_temp_response(0x7FFD);
            return true;
        }
        return false;
    });

    auto ncsi = std::make_shared<dev::ncsi_over_mctp_huawei>(*m_mctp);
    m_cooling->start_ncsi_update_task_huawei(ncsi, mc::milliseconds(1000), 1);

    bool result = m_cooling->get_om_temp_by_ncsi(1);
    EXPECT_FALSE(result);
    
    m_cooling->stop_ncsi_update_task();
    std::this_thread::sleep_for(std::chrono::milliseconds(100));
}

TEST_F(optical_module_cooling_test, get_om_temp_by_ncsi_failure) {
    dev::set_mctp_request_handler([](const mc::dict&, const std::vector<uint8_t>&,
                                     std::string&) { return false; });

    auto ncsi = std::make_shared<dev::ncsi_over_mctp_huawei>(*m_mctp);
    m_cooling->start_ncsi_update_task_huawei(ncsi, mc::milliseconds(1000), 1);

    bool result = m_cooling->get_om_temp_by_ncsi(1);
    EXPECT_FALSE(result);
    
    m_cooling->stop_ncsi_update_task();
    std::this_thread::sleep_for(std::chrono::milliseconds(100));
}

TEST_F(optical_module_cooling_test, get_om_temp_by_ncsi_special_values) {
    // 测试特殊值：0x7FFE (不可用), 0x7FFF (读取失败)
    std::vector<uint16_t> special_values = {0x7FFE, 0x7FFF};
    for (auto temp_value : special_values) {
        dev::set_mctp_request_handler([temp_value](const mc::dict&, const std::vector<uint8_t>& data,
                                                  std::string& rsp) {
            if (data.size() >= COMMON_DATA_SIZE && data[5] == OEM_HUAWEI_GET_OM_TEMP) {
                rsp = make_get_om_temp_response(temp_value);
                return true;
            }
            return false;
        });

        auto ncsi = std::make_shared<dev::ncsi_over_mctp_huawei>(*m_mctp);
        m_cooling->start_ncsi_update_task_huawei(ncsi, mc::milliseconds(1000), 1);

        bool result = m_cooling->get_om_temp_by_ncsi(1);
        EXPECT_FALSE(result);
        
        m_cooling->stop_ncsi_update_task();
        std::this_thread::sleep_for(std::chrono::milliseconds(50));
    }
}

TEST_F(optical_module_cooling_test, get_optical_module_info_by_ncsi_success) {
    dev::set_mctp_request_handler([](const mc::dict&, const std::vector<uint8_t>&,
                                     std::string& rsp) {
        rsp = make_optical_module_info_response("HUAWEI", "TEST-PART", "TEST-SERIAL", 1, 0x07, 100, 850);
        return true;
    });

    auto ncsi = std::make_shared<dev::ncsi_over_mctp_huawei>(*m_mctp);
    m_cooling->start_ncsi_update_task_huawei(ncsi, mc::milliseconds(1000), 1);

    bool result = m_cooling->get_optical_module_info_by_ncsi(1);
    EXPECT_TRUE(result);
    // alarm_low_temp_threshold = 10, alarm_high_temp_threshold = 90
    EXPECT_EQ(m_cooling->TemperatureLowerThresholdCritical.get_value().as<uint16_t>(), 10);
    EXPECT_EQ(m_cooling->TemperatureUpperThresholdCritical.get_value().as<uint16_t>(), 90);
    
    m_cooling->stop_ncsi_update_task();
    std::this_thread::sleep_for(std::chrono::milliseconds(100));
}

TEST_F(optical_module_cooling_test, get_optical_module_info_by_ncsi_invalid_medium_type) {
    dev::set_mctp_request_handler([](const mc::dict&, const std::vector<uint8_t>&,
                                     std::string& rsp) {
        // 使用不支持的medium_type
        rsp = make_optical_module_info_response("HUAWEI", "TEST-PART", "TEST-SERIAL", 0xFF, 0x07, 100, 850);
        return true;
    });

    auto ncsi = std::make_shared<dev::ncsi_over_mctp_huawei>(*m_mctp);
    m_cooling->start_ncsi_update_task_huawei(ncsi, mc::milliseconds(1000), 1);

    bool result = m_cooling->get_optical_module_info_by_ncsi(1);
    EXPECT_FALSE(result);
    
    m_cooling->stop_ncsi_update_task();
    std::this_thread::sleep_for(std::chrono::milliseconds(100));
}

TEST_F(optical_module_cooling_test, get_optical_module_info_by_ncsi_failure) {
    dev::set_mctp_request_handler([](const mc::dict&, const std::vector<uint8_t>&,
                                     std::string&) { return false; });

    auto ncsi = std::make_shared<dev::ncsi_over_mctp_huawei>(*m_mctp);
    m_cooling->start_ncsi_update_task_huawei(ncsi, mc::milliseconds(1000), 1);

    bool result = m_cooling->get_optical_module_info_by_ncsi(1);
    EXPECT_FALSE(result);
    
    m_cooling->stop_ncsi_update_task();
    std::this_thread::sleep_for(std::chrono::milliseconds(100));
}

TEST_F(optical_module_cooling_test, start_ncsi_update_task_huawei_sets_ncsi_object) {
    dev::set_mctp_request_handler([](const mc::dict&, const std::vector<uint8_t>& data,
                                     std::string& rsp) {
        if (data.size() >= COMMON_DATA_SIZE && data[5] == OEM_HUAWEI_GET_OM_TEMP) {
            rsp = make_get_om_temp_response(0x1234);
            return true;
        } else {
            rsp = make_optical_module_info_response();
            return true;
        }
    });

    auto ncsi = std::make_shared<dev::ncsi_over_mctp_huawei>(*m_mctp);
    m_cooling->start_ncsi_update_task_huawei(ncsi, mc::milliseconds(100), 1);

    bool result1 = m_cooling->get_om_temp_by_ncsi(1);
    EXPECT_TRUE(result1);
    bool result2 = m_cooling->get_optical_module_info_by_ncsi(1);
    EXPECT_TRUE(result2);
    
    m_cooling->stop_ncsi_update_task();
    std::this_thread::sleep_for(std::chrono::milliseconds(100));
}

TEST_F(optical_module_cooling_test, stop_ncsi_update_task_cleans_up_resources) {
    auto ncsi = std::make_shared<dev::ncsi_over_mctp_huawei>(*m_mctp);
    m_cooling->start_ncsi_update_task_huawei(ncsi, mc::milliseconds(100), 1);
    m_cooling->stop_ncsi_update_task();
    m_cooling->stop_ncsi_update_task();  // 再次调用应该不会崩溃
    std::this_thread::sleep_for(std::chrono::milliseconds(100));
}

TEST_F(optical_module_cooling_test, update_om_temp_by_smbus_success) {
    m_smbus = mc::make_shared<mock_smbus>();
    
    // 设置SMBus响应：两个字节表示温度值（小端序）
    // 0x1234 = 0x34, 0x12
    std::string response_data = "\x34\x12\x56\x78";  // 多个端口的温度值
    m_smbus->set_send_request_result_for_opcode(0x0400, response_data);
    m_cooling->start_smbus_update_task(m_smbus, mc::milliseconds(1000), 0);

    m_cooling->update_om_temp_by_smbus(0);
    EXPECT_EQ(m_cooling->TemperatureCelsius.get_value().as<uint16_t>(), 0x1234);
    
    m_cooling->stop_smbus_update_task();
    std::this_thread::sleep_for(std::chrono::milliseconds(100));
}

TEST_F(optical_module_cooling_test, update_om_temp_by_smbus_special_values) {
    m_smbus = mc::make_shared<mock_smbus>();
    
    // 测试特殊值：0x7FFD (无效), 0x7FFE (不可用), 0x7FFF (读取失败)
    std::vector<uint16_t> special_values = {0x7FFD, 0x7FFE, 0x7FFF};
    for (auto temp_value : special_values) {
        std::string response_data;
        response_data.push_back(static_cast<uint8_t>(temp_value & 0xFF));
        response_data.push_back(static_cast<uint8_t>((temp_value >> 8) & 0xFF));
        m_smbus->set_send_request_result_for_opcode(0x0400, response_data);
        m_cooling->start_smbus_update_task(m_smbus, mc::milliseconds(1000), 0);

        m_cooling->update_om_temp_by_smbus(0);
        EXPECT_EQ(m_cooling->TemperatureCelsius.get_value().as<uint16_t>(), 0xFFFF);
        
        m_cooling->stop_smbus_update_task();
        std::this_thread::sleep_for(std::chrono::milliseconds(50));
    }
}

TEST_F(optical_module_cooling_test, update_om_temp_by_smbus_empty_response) {
    m_smbus = mc::make_shared<mock_smbus>();
    m_smbus->set_send_request_result_for_opcode(0x0400, "");
    m_cooling->start_smbus_update_task(m_smbus, mc::milliseconds(1000), 0);

    m_cooling->update_om_temp_by_smbus(0);
    // 空响应不应该更新温度值
    
    m_cooling->stop_smbus_update_task();
    std::this_thread::sleep_for(std::chrono::milliseconds(100));
}

TEST_F(optical_module_cooling_test, update_om_temp_by_smbus_different_ports) {
    m_smbus = mc::make_shared<mock_smbus>();
    
    // 设置多个端口的温度值
    std::string response_data = "\x34\x12\x56\x78\x9A\xBC";  // 3个端口的温度值
    m_smbus->set_send_request_result_for_opcode(0x0400, response_data);
    m_cooling->start_smbus_update_task(m_smbus, mc::milliseconds(1000), 0);

    m_cooling->update_om_temp_by_smbus(0);
    EXPECT_EQ(m_cooling->TemperatureCelsius.get_value().as<uint16_t>(), 0x1234);
    
    m_cooling->update_om_temp_by_smbus(1);
    EXPECT_EQ(m_cooling->TemperatureCelsius.get_value().as<uint16_t>(), 0x7856);
    
    m_cooling->stop_smbus_update_task();
    std::this_thread::sleep_for(std::chrono::milliseconds(100));
}

TEST_F(optical_module_cooling_test, start_smbus_update_task_with_null_pointer) {
    m_cooling->start_smbus_update_task(nullptr, mc::milliseconds(1000), 0);
    // 应该不会崩溃，但也不会启动任务
    EXPECT_TRUE(true);
}

TEST_F(optical_module_cooling_test, stop_smbus_update_task_cleans_up_resources) {
    m_smbus = mc::make_shared<mock_smbus>();
    m_cooling->start_smbus_update_task(m_smbus, mc::milliseconds(100), 0);
    m_cooling->stop_smbus_update_task();
    m_cooling->stop_smbus_update_task();  // 再次调用应该不会崩溃
    std::this_thread::sleep_for(std::chrono::milliseconds(100));
}

TEST_F(optical_module_cooling_test, stop_smbus_update_task_without_start) {
    m_cooling->stop_smbus_update_task();
    EXPECT_TRUE(true);
}

// ========== OpticalModule_Current 测试 ==========

// Test fixture for OpticalModule_Current
class optical_module_current_test : public mc::test::TestWithEngine {
protected:
    static void SetUpTestSuite() {
        TestWithEngine::SetUpTestSuite();
        m_test_service.init();
        m_test_service.start();
        m_mctp = mc::make_shared<dev::mctp>(nullptr, 0, dev::MCTP_MESSAGE_TYPE_NCSI, "");
        m_current = mc::make_shared<dev::OpticalModule_Current>();
    }

    static void TearDownTestSuite() {
        m_test_service.stop();
        m_current.reset();
        m_mctp.reset();
        TestWithEngine::TearDownTestSuite();
    }

    void SetUp() override {
    }

    void TearDown() override {
        // 等待所有异步操作完成（如定时器回调），避免在服务停止时回调仍在执行
        std::this_thread::sleep_for(std::chrono::milliseconds(200));
        dev::set_mctp_request_handler(nullptr);
    }

    static test_service m_test_service;
    static mc::shared_ptr<dev::mctp> m_mctp;
    static mc::shared_ptr<dev::OpticalModule_Current> m_current;
};

// 静态成员初始化
test_service optical_module_current_test::m_test_service{"bmc.kepler.test_om_current"};
mc::shared_ptr<dev::mctp> optical_module_current_test::m_mctp;
mc::shared_ptr<dev::OpticalModule_Current> optical_module_current_test::m_current;

TEST_F(optical_module_current_test, get_optical_module_current_by_ncsi_success) {
    dev::set_mctp_request_handler([](const mc::dict&, const std::vector<uint8_t>&,
                                     std::string& rsp) {
        rsp = make_optical_module_info_response("HUAWEI", "TEST-PART", "TEST-SERIAL", 1, 0x07, 100, 850);
        return true;
    });

    auto ncsi = std::make_shared<dev::ncsi_over_mctp_huawei>(*m_mctp);
    m_current->start_ncsi_update_task_huawei(ncsi, mc::milliseconds(1000), 1);

    bool result = m_current->get_optical_module_current_by_ncsi(1);
    EXPECT_TRUE(result);
    // working_tx_bias = 5000 (milliamps)
    auto current_value = m_current->TXBiasCurrentMilliAmps.get_value().as<std::vector<double>>();
    EXPECT_EQ(current_value.size(), 1);
    EXPECT_NEAR(current_value[0], 5000.0, 0.01);
    
    m_current->stop_ncsi_update_task();
    std::this_thread::sleep_for(std::chrono::milliseconds(100));
}

TEST_F(optical_module_current_test, get_optical_module_current_by_ncsi_failure) {
    dev::set_mctp_request_handler([](const mc::dict&, const std::vector<uint8_t>&,
                                     std::string&) { return false; });

    auto ncsi = std::make_shared<dev::ncsi_over_mctp_huawei>(*m_mctp);
    m_current->start_ncsi_update_task_huawei(ncsi, mc::milliseconds(1000), 1);

    bool result = m_current->get_optical_module_current_by_ncsi(1);
    EXPECT_FALSE(result);
    
    m_current->stop_ncsi_update_task();
    std::this_thread::sleep_for(std::chrono::milliseconds(100));
}

TEST_F(optical_module_current_test, start_ncsi_update_task_huawei_sets_ncsi_object) {
    dev::set_mctp_request_handler([](const mc::dict&, const std::vector<uint8_t>&,
                                     std::string& rsp) {
        rsp = make_optical_module_info_response();
        return true;
    });

    auto ncsi = std::make_shared<dev::ncsi_over_mctp_huawei>(*m_mctp);
    m_current->start_ncsi_update_task_huawei(ncsi, mc::milliseconds(100), 1);

    bool result = m_current->get_optical_module_current_by_ncsi(1);
    EXPECT_TRUE(result);
    
    m_current->stop_ncsi_update_task();
    std::this_thread::sleep_for(std::chrono::milliseconds(100));
}

TEST_F(optical_module_current_test, stop_ncsi_update_task_cleans_up_resources) {
    auto ncsi = std::make_shared<dev::ncsi_over_mctp_huawei>(*m_mctp);
    m_current->start_ncsi_update_task_huawei(ncsi, mc::milliseconds(100), 1);
    m_current->stop_ncsi_update_task();
    m_current->stop_ncsi_update_task();  // 再次调用应该不会崩溃
    std::this_thread::sleep_for(std::chrono::milliseconds(100));
}

TEST_F(optical_module_current_test, stop_ncsi_update_task_without_start) {
    m_current->stop_ncsi_update_task();
    EXPECT_TRUE(true);
}

// ========== OpticalModule_Power 测试 ==========

// Test fixture for OpticalModule_Power
class optical_module_power_test : public mc::test::TestWithEngine {
protected:
    static void SetUpTestSuite() {
        TestWithEngine::SetUpTestSuite();
        m_test_service.init();
        m_test_service.start();
        m_mctp = mc::make_shared<dev::mctp>(nullptr, 0, dev::MCTP_MESSAGE_TYPE_NCSI, "");
        m_power = mc::make_shared<dev::OpticalModule_Power>();
    }

    static void TearDownTestSuite() {
        m_test_service.stop();
        m_power.reset();
        m_mctp.reset();
        TestWithEngine::TearDownTestSuite();
    }

    void SetUp() override {
    }

    void TearDown() override {
        // 等待所有异步操作完成（如定时器回调），避免在服务停止时回调仍在执行
        std::this_thread::sleep_for(std::chrono::milliseconds(200));
        dev::set_mctp_request_handler(nullptr);
    }

    static test_service m_test_service;
    static mc::shared_ptr<dev::mctp> m_mctp;
    static mc::shared_ptr<dev::OpticalModule_Power> m_power;
};

// 静态成员初始化
test_service optical_module_power_test::m_test_service{"bmc.kepler.test_om_power"};
mc::shared_ptr<dev::mctp> optical_module_power_test::m_mctp;
mc::shared_ptr<dev::OpticalModule_Power> optical_module_power_test::m_power;

TEST_F(optical_module_power_test, get_optical_module_power_by_ncsi_success) {
    dev::set_mctp_request_handler([](const mc::dict&, const std::vector<uint8_t>&,
                                     std::string& rsp) {
        rsp = make_optical_module_info_response("HUAWEI", "TEST-PART", "TEST-SERIAL", 1, 0x07, 100, 850);
        return true;
    });

    auto ncsi = std::make_shared<dev::ncsi_over_mctp_huawei>(*m_mctp);
    m_power->start_ncsi_update_task_huawei(ncsi, mc::milliseconds(1000), 1);

    bool result = m_power->get_optical_module_power_by_ncsi(1);
    EXPECT_TRUE(result);
    // working_tx_power = 6000, working_rx_power = 7000 (milliwatts)
    auto tx_power = m_power->TXOutputPowerMilliWatts.get_value().as<std::vector<double>>();
    auto rx_power = m_power->RXInputPowerMilliWatts.get_value().as<std::vector<double>>();
    EXPECT_EQ(tx_power.size(), 1);
    EXPECT_EQ(rx_power.size(), 1);
    EXPECT_NEAR(tx_power[0], 6000.0, 0.01);
    EXPECT_NEAR(rx_power[0], 7000.0, 0.01);
    // alarm_tx_power_threshold = 8000, alarm_rx_power_threshold = 9000
    EXPECT_EQ(m_power->TXPowerUpperThresholdCritical.get_value().as<uint16_t>(), 8000);
    EXPECT_EQ(m_power->RXPowerUpperThresholdCritical.get_value().as<uint16_t>(), 9000);
    
    m_power->stop_ncsi_update_task();
    std::this_thread::sleep_for(std::chrono::milliseconds(100));
}

TEST_F(optical_module_power_test, get_optical_module_power_by_ncsi_invalid_thresholds) {
    dev::set_mctp_request_handler([](const mc::dict&, const std::vector<uint8_t>&,
                                     std::string& rsp) {
        oem_huawei_optical_module_info_rsp_t response{};
        response.public_rsp_header.response_code   = host_to_be16(0);
        response.public_rsp_header.reason_code     = host_to_be16(0);
        response.public_rsp_header.manufacturer_id = HUAWEI_MANUFACTURE_ID;
        response.public_rsp_header.sub_command_id  = OEM_HUAWEI_GET_OPTICAL_MODULE_INFO;
        std::memset(response.vendor, ' ', MCTP_NCSI_OPTICAL_MODULE_FIELD_LEN);
        std::memset(response.part_number, ' ', MCTP_NCSI_OPTICAL_MODULE_FIELD_LEN);
        std::memset(response.serial_number, ' ', MCTP_NCSI_OPTICAL_MODULE_FIELD_LEN);
        response.type                = 1;
        response.connector           = 0x07;
        response.transceiver_distance = host_to_be16(100);
        response.wave_length         = host_to_be16(850);
        response.working_voltage     = host_to_be16(3300);
        response.working_tx_bias     = host_to_be16(5000);
        response.working_tx_power    = host_to_be16(6000);
        response.working_rx_power    = host_to_be16(7000);
        response.alarm_tx_power_threshold = host_to_be16(0xFFFF);  // 无效值
        response.alarm_rx_power_threshold = host_to_be16(0xFFFF);  // 无效值
        response.alarm_low_temp_threshold = host_to_be16(10);
        response.alarm_high_temp_threshold = host_to_be16(90);
        response.rx_los_state        = 0;
        response.tx_full_state       = 0;
        rsp = std::string(reinterpret_cast<const char*>(&response),
                          OEM_HUAWEI_OPTICAL_MODULE_INFO_RSP_LEN);
        return true;
    });

    auto ncsi = std::make_shared<dev::ncsi_over_mctp_huawei>(*m_mctp);
    m_power->start_ncsi_update_task_huawei(ncsi, mc::milliseconds(1000), 1);

    bool result = m_power->get_optical_module_power_by_ncsi(1);
    EXPECT_TRUE(result);
    // 无效阈值不应该被设置
    // 注意：这里需要检查属性是否被设置，但由于0xFFFF不会被设置，所以属性值应该保持默认值
    
    m_power->stop_ncsi_update_task();
    std::this_thread::sleep_for(std::chrono::milliseconds(100));
}

TEST_F(optical_module_power_test, get_optical_module_power_by_ncsi_failure) {
    dev::set_mctp_request_handler([](const mc::dict&, const std::vector<uint8_t>&,
                                     std::string&) { return false; });

    auto ncsi = std::make_shared<dev::ncsi_over_mctp_huawei>(*m_mctp);
    m_power->start_ncsi_update_task_huawei(ncsi, mc::milliseconds(1000), 1);

    bool result = m_power->get_optical_module_power_by_ncsi(1);
    EXPECT_FALSE(result);
    
    m_power->stop_ncsi_update_task();
    std::this_thread::sleep_for(std::chrono::milliseconds(100));
}

TEST_F(optical_module_power_test, start_ncsi_update_task_huawei_sets_ncsi_object) {
    dev::set_mctp_request_handler([](const mc::dict&, const std::vector<uint8_t>&,
                                     std::string& rsp) {
        rsp = make_optical_module_info_response();
        return true;
    });

    auto ncsi = std::make_shared<dev::ncsi_over_mctp_huawei>(*m_mctp);
    m_power->start_ncsi_update_task_huawei(ncsi, mc::milliseconds(100), 1);

    bool result = m_power->get_optical_module_power_by_ncsi(1);
    EXPECT_TRUE(result);
    
    m_power->stop_ncsi_update_task();
    std::this_thread::sleep_for(std::chrono::milliseconds(100));
}

TEST_F(optical_module_power_test, stop_ncsi_update_task_cleans_up_resources) {
    auto ncsi = std::make_shared<dev::ncsi_over_mctp_huawei>(*m_mctp);
    m_power->start_ncsi_update_task_huawei(ncsi, mc::milliseconds(100), 1);
    m_power->stop_ncsi_update_task();
    m_power->stop_ncsi_update_task();  // 再次调用应该不会崩溃
    std::this_thread::sleep_for(std::chrono::milliseconds(100));
}

TEST_F(optical_module_power_test, stop_ncsi_update_task_without_start) {
    m_power->stop_ncsi_update_task();
    EXPECT_TRUE(true);
}

} // namespace

